//
//  HousingDetailsViewController.m
//  EMMApp
//
//  Created by Mac on 16/7/1.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "HousingDetailsViewController.h"
#import "EMMTouristsViewController.h"
#import "AddNewSignViewController.h"
#import "AddSubscriptionViewController.h"

/** ViewController
 *
 *  ViewController导入.h文件
 */
#import "CalculatePriceViewController.h"
#import "EMMPhotoViewController.h"

/** Cell
 *
 *  Cell导入.h文件
 */
#import "KnowDetailCell.h"

/** Api
 *
 *  首页Api调用导入.h文件
 */
#import "AddProjectRealMapApi.h"
#import "GetHousesDetailApi.h"

/** 系统库与第三方文件
 *
 *  系统库与第三方文件调用导入.h文件
 */
#import "NSString+Base64.h"
#import "NSData+Base64.h"
#import <AVFoundation/AVFoundation.h>
#import "QBImagePickerController.h"
#import "VGReturnPartPicViewCell.h"

@interface HousingDetailsViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,QBImagePickerControllerDelegate,UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate> {
   
    
}

/**
 *  存对应的数据字典
 */
@property(nonatomic,strong) NSMutableDictionary *housingdic;

/**
 *  二级列表是否展开状态
 */
@property(nonatomic,strong) NSMutableArray *selectedArr;


/**
 *  列表左侧显示数据数组
 */
@property(nonatomic,strong) NSMutableArray *grouparr0;

/**
 *  创建UITableView 命名:housingDetailsTableView
 */
@property (nonatomic, strong) UITableView *housingDetailsTableView;

/**
 *  GetHousesDetail - model
 */
@property (nonatomic, strong) GetHousesDetail *getHousesDetail;

/**
 *  图片数组
 */
@property(nonatomic,strong) NSMutableArray* picArray;

/**
 *  数据源数组
 */
@property (nonatomic, strong) NSMutableArray *realMapList;

@property (nonatomic, weak) UIButton *signBtn;
@property (nonatomic, weak) UIButton *subcribeBtn;

@end

@implementation HousingDetailsViewController

#pragma makr - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNavigationController];
    _picArray = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    _housingdic = [[NSMutableDictionary alloc] init];
    _selectedArr = [[NSMutableArray alloc] initWithObjects:@"0",nil];
    _realMapList = [[NSMutableArray alloc] init];
    [self showHudInWindow:@"正在请求稍等......"];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [self postGetHousesDetailApi];
    });
    _housingDetailsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight-70) style:UITableViewStylePlain];
    _housingDetailsTableView.delegate = self;
    _housingDetailsTableView.dataSource = self;
    _housingDetailsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _housingDetailsTableView.backgroundColor = [UIColor whiteColor];
    _housingDetailsTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_housingDetailsTableView];
    [self initDataSource];
    
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
//    btn.frame = CGRectMake(10, EMM_HEIGHT-70-SafeAreaTopHeight, EMM_WIDTH-20, 50);
//    [btn setTitle:@"算价" forState:UIControlStateNormal];
//    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    btn.titleLabel.font = [UIFont systemFontOfSize:16];
//    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
//    btn.backgroundColor = [UIColor colorFromHexCode:@"#ff7200"];
//    btn.layer.masksToBounds = YES;
//    btn.layer.cornerRadius = 4;
//    [self.view addSubview:btn];
    
    // 只有可售的状态才显示一下入口
    CGFloat margin = 10;
    UIButton *subscribeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    subscribeBtn.frame = CGRectMake(margin, EMM_HEIGHT-70-SafeAreaTopHeight, (EMM_WIDTH - (margin * 4)) * 0.5, 50);
    [subscribeBtn setTitle:@"认购" forState:UIControlStateNormal];
    [subscribeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    subscribeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [subscribeBtn addTarget:self action:@selector(subscribeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    subscribeBtn.backgroundColor = [UIColor colorFromHexCode:@"#ff7200"];
    subscribeBtn.layer.masksToBounds = YES;
    subscribeBtn.layer.cornerRadius = 4;
    subscribeBtn.hidden = YES;
    [self.view addSubview:subscribeBtn];
    self.subcribeBtn = subscribeBtn;
    
    UIButton *signBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    signBtn.frame = CGRectMake(subscribeBtn.frame.size.width + (margin * 3), subscribeBtn.frame.origin.y, subscribeBtn.frame.size.width, 50);
    [signBtn setTitle:@"签约" forState:UIControlStateNormal];
    [signBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    signBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [signBtn addTarget:self action:@selector(signBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    signBtn.backgroundColor = [UIColor colorFromHexCode:@"#FB5A3B"];
    signBtn.layer.masksToBounds = YES;
    signBtn.layer.cornerRadius = 4;
    signBtn.hidden = YES;
    [self.view addSubview:signBtn];
    self.signBtn = signBtn;
    
    
}


/* 认购权限*/
-(BOOL)isAddSubscribe_promise{
    
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *status =  [userdf objectForKey:@"isAddSubscribe"];
    
    BOOL isAddSubscribe = [status boolValue];
    NSLog(@"%f",isAddSubscribe);
    return  isAddSubscribe;
    
}

/* 签约权限*/
-(BOOL)isAddSigned_promise{
    
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *status =  [userdf objectForKey:@"isAddSigned"];
    
    BOOL isAddSigned = [status boolValue];
    NSLog(@"%f",isAddSigned);
    return  isAddSigned;
}


#pragma mark - 导航创建
/**
 *  功能
 */
- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"房源详情";
    [self configLeftBtn];
}

#pragma mark - 生命周期函数调用方法
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

#pragma mark - 房源详情数据Api调用方法
/**
 *  功能描述：
 *  房源详情Api接口
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)postGetHousesDetailApi {
    [_realMapList removeAllObjects];
    GetHousesDetailApi *api = [[GetHousesDetailApi alloc] initWithRoomId:self.roomId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetHousesDetailApi *result = (GetHousesDetailApi *)request;
        if (result.isSuccess) {
            [self hideHud];
            GetHousesDetail *get = result.resultData;
            _getHousesDetail = get;
           
            // 判断当前房源状态 只有可售状态才可进行认购签约操作
            self.signBtn.hidden = !([get.housesStatus isEqualToString:@"可售"]&&[self isAddSigned_promise]);
            self.subcribeBtn.hidden = !([get.housesStatus isEqualToString:@"可售"]&&[self isAddSubscribe_promise]);
           
            for (RealMapList *list in get.realMapList) {
                [_realMapList addObject:list];
            }
        } else {
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                [appInstance showLogin];
                
            } else if ( [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
        [_housingDetailsTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - methods
- (void)signBtnClick:(UIButton *)btn {
    // 新增签约
    AddNewSignViewController *nvc = [[AddNewSignViewController alloc] init];
    nvc.customerId = nil;
    nvc.isAdd = YES;
    nvc.paymentMethod = nil;
    nvc.floorType = @"0";
    nvc.busReturnType = @"0";
    nvc.konString = @"0";
    nvc.qyRoomName = self.getHousesDetail.housesName;
    nvc.qyRoomId = self.roomId;
    nvc.calculateArea = self.getHousesDetail.buildingArea;
    nvc.discountPrice = self.getHousesDetail.buildingPrice;
    nvc.discountTotalPrice = self.getHousesDetail.totalAmount;
    nvc.discountAfterAmount = self.getHousesDetail.totalAmount;
    nvc.houseDetailTo = YES;
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    nvc.jJRDataArr = arr;
    [self.navigationController pushViewController:nvc animated:YES];

}

- (void)subscribeBtnClick:(UIButton *)btn {
    // 新增认购
    GetSubscribeDetail *get = [[GetSubscribeDetail alloc] init];
    get.subscribeHouses = self.getHousesDetail.housesName;
    get.calculateArea = self.getHousesDetail.buildingArea;
    get.discountPrice = self.getHousesDetail.buildingPrice;
    get.discountTotalPrice = self.getHousesDetail.totalAmount;
    get.discountAfterAmount = self.getHousesDetail.totalAmount;
    get.roomId = self.roomId;
    AddSubscriptionViewController *nvc = [[AddSubscriptionViewController alloc] init];
    nvc.isSFNew = @"0";
    nvc.customerId = nil;
    nvc.HouseingDetailTo = YES;
    nvc.getSubscribeDetail = get;
    [self.navigationController pushViewController:nvc animated:YES];
        
}

#pragma mark - 算价按钮触发事件调用方法
//- (void)btnClick:(UIButton *)btn {
//    CalculatePriceViewController *evc = [[CalculatePriceViewController alloc] init];
//    evc.getHousesDetail = _getHousesDetail;
//    evc.roomId = self.roomId;
//    [self.navigationController pushViewController:evc animated:YES];
//}



#pragma mark - 列表左侧显示数据初始化
/**
 *  功能描述：
 *  列表左侧显示数据初始化
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
-(void)initDataSource {
    _grouparr0 = [[NSMutableArray alloc] initWithObjects:
                 @"客户姓名",@"经纪人姓名",@"房源状态",@"计价方式",@"户型",@"建筑面积",@"套内面积",
                 @"分摊面积",@"赠送面积",@"建筑单价", @"套内单价",@"总价",@"",nil];
    [_housingdic setValue:_grouparr0 forKey:@"0"];
}

#pragma mark - UITableView代理
/**
 *  功能描述：
 *  UITabelView代理方法
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
//返回几个表头
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

//每一个表头下返回几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *string = [NSString stringWithFormat:@"%ld",section];
    if ([_selectedArr containsObject:string]) {
        NSArray *array1 = _housingdic[string];
        return array1.count;
    }
    return 0;
}

//设置表头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

//Section Footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 5)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

//设置view，将替代titleForHeaderInSection方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, tableView.frame.size.width-20, 50)];
    
    titleLabel.text = [  _getHousesDetail.housesName stringByReplacingOccurrencesOfString:@"-->"withString:@"-"];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textColor = [UIColor colorFromHexCode:@"#1A1A1A"];
    titleLabel.numberOfLines = 0;
    [view addSubview:titleLabel];
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-20, 0.5)];
    lineImage.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
   
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, EMM_WIDTH, 50);
    button.tag = 100+section;
//    [button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    view.backgroundColor = [UIColor colorFromHexCode:@"#fff5e9"];
    UILabel *sLabel6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 2, 30)];
    sLabel6.backgroundColor = [UIColor colorFromHexCode:@"#ff7200"];
    [view addSubview:sLabel6];
    UIImageView *upImageView = [[UIImageView alloc] initWithFrame:CGRectMake(EMM_WIDTH-40, 15, 25, 15)];
//    [view addSubview:upImageView];
    NSString *string = [NSString stringWithFormat:@"%ld",section];
    if ([_selectedArr containsObject:string]) {
        upImageView.image = [UIImage imageNamed:@"sanjt_down"];
    }else {
        upImageView.image = [UIImage imageNamed:@"sanjt_up"];
    }
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 12) {
        return 100;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *indexStr = [NSString stringWithFormat:@"%ld",indexPath.section];
    static NSString *CellIdentifier = @"KnowDetailCellId";
    KnowDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"KnowDetailCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([_selectedArr containsObject:indexStr]) {
        cell.titleLabel.text = _housingdic[indexStr][indexPath.row];
    }
    
    if (indexPath.row == 12) {
        UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 99.5, EMM_WIDTH-20, 0.5)];
        lineImage.backgroundColor = [UIColor colorFromHexCode:@"f0f0f0"];
        [cell addSubview:lineImage];
    } else {
        UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-20, 0.5)];
        lineImage.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:lineImage];
    }
    if(indexPath.row == 0) {
        cell.fbTitleLabel.text = _getHousesDetail.customerName;
    }else if (indexPath.row == 1) {
       cell.fbTitleLabel.text = _getHousesDetail.userName;
    }
    else if (indexPath.row == 2) {
        cell.fbTitleLabel.text = _getHousesDetail.housesStatus;
    } else if (indexPath.row == 3) {
        cell.fbTitleLabel.text = _getHousesDetail.pricingMode;
    } else if (indexPath.row == 4) {
        cell.fbTitleLabel.text = _getHousesDetail.housesType;
    } else if (indexPath.row == 5) {
        if ([NSString isStringEmpty2:_getHousesDetail.buildingArea] == NO) {
            cell.fbTitleLabel.text = [NSString stringWithFormat:@"%@m²",_getHousesDetail.buildingArea];
        } else {
            cell.fbTitleLabel.text =@"m²";
        }
    } else if (indexPath.row == 6) {
        if ([NSString isStringEmpty2:_getHousesDetail.innerArea] == NO) {
            cell.fbTitleLabel.text = [NSString stringWithFormat:@"%@m²",_getHousesDetail.innerArea];
        } else {
            cell.fbTitleLabel.text =@"m²";
        }
    } else if (indexPath.row == 7) {
        if ([NSString isStringEmpty2:_getHousesDetail.sharingArea] == NO) {
            cell.fbTitleLabel.text = [NSString stringWithFormat:@"%@m²",_getHousesDetail.sharingArea];
        } else {
            cell.fbTitleLabel.text =@"m²";
        }
    } else if (indexPath.row == 8) {
        if ([NSString isStringEmpty2:_getHousesDetail.freeArea] == NO) {
            cell.fbTitleLabel.text = [NSString stringWithFormat:@"%@m²",_getHousesDetail.freeArea];
        } else {
            cell.fbTitleLabel.text =@"m²";
        }
    } else if (indexPath.row == 9) {
        if ([NSString isStringEmpty2:_getHousesDetail.buildingPrice] == NO) {
            cell.fbTitleLabel.text = [NSString stringWithFormat:@"%@元/m²",_getHousesDetail.buildingPrice];
        } else {
            cell.fbTitleLabel.text = @"元/m²";
        }
    } else if (indexPath.row == 10) {
        if ([NSString isStringEmpty2:_getHousesDetail.innerPrice] == NO) {
            cell.fbTitleLabel.text = [NSString stringWithFormat:@"%@元/m²",_getHousesDetail.innerPrice];
        } else {
            cell.fbTitleLabel.text = @"元/m²";
        }
    } else if (indexPath.row == 11) {
        if ([NSString isStringEmpty2:_getHousesDetail.totalAmount] == NO) {
            cell.fbTitleLabel.text = [NSString stringWithFormat:@"%@万元",_getHousesDetail.totalAmount];
        } else {
            cell.fbTitleLabel.text = @"万元";
        }
    } else if (indexPath.row == 12) {
        UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 80, 80)];
        imageView2.image =[UIImage imageNamed:@"fyuan_img"];
        [cell addSubview:imageView2];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 64, SafeAreaTopHeight)];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 2;
        [imageView2 addSubview:imageView];
        UIButton *btnImageXS = [UIButton buttonWithType:UIButtonTypeSystem];
        btnImageXS.frame = CGRectMake(10, 10, 80, 80);
        [btnImageXS addTarget:self action:@selector(btnImageXSClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:btnImageXS];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, (100-20)/2, 40, 20)];
        label.font = [UIFont systemFontOfSize:15];
        [cell addSubview:label];
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(140, 10, 80, 80)];
        imageView1.image = [UIImage imageNamed:@"fyuan_photo"];
        [cell addSubview:imageView1];
        UIButton *btnImage = [UIButton buttonWithType:UIButtonTypeSystem];
        btnImage.frame = CGRectMake(170, 10, 80, 80);
        [btnImage addTarget:self action:@selector(btnImageClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:btnImage];        
        if (_realMapList.count > 0) {
            RealMapList *list = [_realMapList objectAtIndex:0];
            [imageView sd_setImageWithURL:[NSURL URLWithString:list.realMapUrl] placeholderImage:[UIImage imageNamed:@""]];
            label.text = [NSString stringWithFormat:@"(%ld)",_realMapList.count];
        }else {
            label.text = @"";
            imageView.image = [UIImage imageNamed:@""];
        }
    }
    return cell;
}

#pragma mark - 图片浏览按钮触发事件调用方法
/**
 *  功能描述：
 *  浏览上传的图片功能
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)btnImageXSClick:(UIButton *)btn {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    NSMutableArray *arrId = [[NSMutableArray alloc] init];
    for (int i = 0; i < _realMapList.count; i++) {
        RealMapList *list = [_realMapList objectAtIndex:i];
        [arr addObject:list.realMapUrl];
        [arrId addObject:list.realMapId];
    }
    if (arr.count > 0) {
        EMMPhotoViewController *evc = [[EMMPhotoViewController alloc] init];
        evc.dataArr = arr;
        evc.dataArrId = arrId;
        evc.isYN = YES;
        [self.navigationController pushViewController:evc animated:YES];
        
    }else {
        [self showToast:@"暂无图片预览"];
    }
}

#pragma mark - 是否展开二级列表触发事件调用方法
/**
 *  功能描述：
 *  二级列表展开收起功能
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
-(void)doButton:(UIButton *)sender {
    NSString *string = [NSString stringWithFormat:@"%ld",sender.tag-100];
    //数组selectedArr里面存的数据和表头想对应，方便以后做比较
    if ([_selectedArr containsObject:string]) {
        [_selectedArr removeObject:string];
    } else  {
        [_selectedArr addObject:string];
    }
    [_housingDetailsTableView reloadData];
}

#pragma mark - 选择图片
- (void)btnImageClick:(UIButton *)btn {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark - 新增图片Api调用方法
/**
 *  功能描述：
 *  上传图片Api接口
 *
 *  更新时间：2016/12/30
 *  更新人：wangguiping
 */
- (void)postAddProjectRealMapApi:(NSMutableArray *)realMapList {
    [self showHud:@"正在加载请稍等..."];
    AddProjectRealMapApi *api = [[AddProjectRealMapApi alloc] initWithRealMapList:realMapList];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        AddProjectRealMapApi *result = (AddProjectRealMapApi *)request;
        if (result.isSuccess) {
            [_picArray removeAllObjects];
            [self postGetHousesDetailApi];
        } else {
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
        
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
        [_housingDetailsTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        [self showPhotosFromCamera];
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        [self showSelectPhotos];
       
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - 调用系统相机和相册
////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark camera utility

////////////////////////////////////////////////////////////////////////////////////////////////////

- (BOOL) isCameraAvailable {
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable {
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) canUserPickVideosFromPhotoLibrary {
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) canUserPickPhotosFromPhotoLibrary {
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType {
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark 1 拍照
- (void)showPhotosFromCamera {
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        }
        
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];
    } else {
        [self alertWithTitle:@"无法访问相机" msg:@"在\"设置>隐私>相机>Vgo\"中点击启用."];
    }
}

#pragma mark - UIImagePickerControllerDelegate
#pragma mark 2 拍照
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [self showThisImagePicker:picker info:info];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark 3 拍照
- (void)showThisImagePicker:(UIImagePickerController *)picker info:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData* imageData = UIImageJPEGRepresentation(portraitImg, 0.1);
        if (imageData == NULL) {
            return;
        }
        NSString *base64EncodedString = [NSString base64StringFromData:imageData length:[imageData length]];
        NSString *encodedImageStr = base64EncodedString;
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:encodedImageStr forKey:@"realMapContent"];
        [dict setObject:@".png" forKey:@"realMapType"];
        [arr addObject:dict];
        [self postAddProjectRealMapApi:arr];
    }];
}

#pragma mark 照片
- (void)showSelectPhotos {
    if (![self isPhotoLibraryAvailable]) {
        [self alertWithTitle:@"无法访问相机" msg:@"在\"设置>隐私>照片>Vgo\"中点击启用."];
        return;
    }
    QBImagePickerController *imagePickerController = [QBImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.showsNumberOfSelectedAssets = YES;
    imagePickerController.maximumNumberOfSelection = 5;
    [self presentViewController:imagePickerController animated:YES completion:NULL];
}

#pragma mark - QBImagePickerControllerDelegate
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets {
    NSLog(@"Selected assets:");
    NSLog(@"%@", assets);// addbtn100
    for (ALAsset *result in assets) {
        // ALAsset的类型
        NSString *assetType = [result valueForProperty:ALAssetPropertyType];
        if ([assetType isEqualToString:ALAssetTypePhoto]){
            ALAssetRepresentation *assetRepresentation =[result defaultRepresentation];
            //            CGFloat imageScale = [assetRepresentation scale];
            UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];
            
            CGImageRef imageReference = [assetRepresentation fullResolutionImage];
            // 对找到的图片进行操作
            UIImage *image = [[UIImage alloc] initWithCGImage:imageReference scale:1.0 orientation:imageOrientation];
            if (image != nil){
                VGReturnGoodsPicDTO *v = [[VGReturnGoodsPicDTO alloc] init];
                v.picImage = image;
                v.asset = result;
//                
                [_picArray addObject:v];
                
            } else {
                NSLog(@"Failed to create the image.");
            }
        }
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
    [self cat];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)cat {
    NSMutableArray *strarr = nil;
    for (int i=0; i<_picArray.count; i++) {
        if (!strarr) {
            strarr = [NSMutableArray array];
        }
        VGReturnGoodsPicDTO *dto = [_picArray objectAtIndex:i];
        NSString *base64 = [self postImage:dto.picImage];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:base64 forKey:@"realMapContent"];
        [dict setObject:@".png" forKey:@"realMapType"];
        [strarr addObject:dict];
    }
    [self postAddProjectRealMapApi:strarr];
}

- (NSString *)postImage:(UIImage *)portraitImg {
    //    portraitImg = [portraitImg imageByScalingAndCroppingForSize:CGSizeMake(60, 60)];
    NSData* imageData = UIImageJPEGRepresentation(portraitImg, 0.1);
    if (imageData == NULL) {
        return nil;
    }
    NSString *base64EncodedString = [NSString base64StringFromData:imageData length:[imageData length]];
    NSString *encodedImageStr = base64EncodedString;
    return encodedImageStr;
}

@end
